package com.sfh.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.plugin.activerecord.Page;
import com.sfh.base.BaseController;
import com.sfh.base.ReturnData;
import com.sfh.controller.rsp.RspMass;
import com.sfh.controller.task.TaskUserWealthCharm;
import com.sfh.req.ReqIndex;
import com.sfh.req.ReqMassAdd;
import com.sfh.req.ReqMassDel;
import com.sfh.req.ReqMassPage;
import com.sfh.req.ReqMassQuery;
import com.sfh.req.ReqMassSearch;
import com.sfh.req.ReqMassUpdate;
import com.sfh.req.ReqPage;
import com.sfh.service.Const;
import com.sfh.service.model.MassModel;
import com.sfh.service.model.MessageModel;
import com.sfh.service.model.NoteModel;
import com.sfh.service.model.table.MassTable;
import com.sfh.service.model.table.MessageTable;
import com.sfh.service.model.table.NoteTable;
import com.sfh.service.util.SQLHelp;

public class MassController extends BaseController {
	/***
	 * 推荐社团 7
	 */
	public void queryHomeRecomMass() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) ORDER BY %s DESC LIMIT %d,%d",
					MassTable.Table, 
					MassTable.id, 
					MassTable.id, 
					MassTable.Table, 
					MassTable.size,
					index*7,
					index);
			List<MassModel> page = MassModel.MASS.find(sql);
			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page) {
				list.add(RspMass.createMass(mass));
			}
			this.renderJson(ReturnData.ok(list));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 最新社团 4
	 */
	public void queryHomeNewMass() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) ORDER BY %s DESC LIMIT %d,%d",
					MassTable.Table,
					MassTable.id, 
					MassTable.id, 
					MassTable.Table, 
					MassTable.time, 
					index*4,
					4);
			List<MassModel> page = MassModel.MASS.find(sql);
			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page) {
				list.add(RspMass.createMass(mass));
			}
			this.renderJson(ReturnData.ok(list));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * VIP 社团 9
	 */
	public void queryHomeVIPMass() {
		try {
			int index  = this.getRequestObject(ReqIndex.class).getIndex();
			String sql = String.format(
					" SELECT * FROM %s WHERE %s >= (SELECT floor(RAND() * (SELECT MAX(%s) FROM %s))) AND mass_vip=1  LIMIT %d,%d",
					MassTable.Table, 
					MassTable.id, 
					MassTable.id, 
					MassTable.Table, 
					index*9,
					9);

			List<MassModel> page = MassModel.MASS.find(sql);
			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page) {
				list.add(RspMass.createMass(mass));
			}
			this.renderJson(ReturnData.ok(list));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/**
	 * 获取所有社区{@link ReqPage}
	 */
	public void massPage() {
		try {
			ReqMassPage req = this.getRequestObject(ReqMassPage.class);
			SQLHelp sqlHelp = new SQLHelp(MassTable.Table);

			if ("1".equals(req.getMassType())) {
				sqlHelp.sore("desc", MassTable.size);
			}else if ("2".equals(req.getMassType())){
				sqlHelp.sore("desc", MassTable.time);
			}else if ("3".equals(req.getMassType())){
				sqlHelp.addWhereEqualTo(MassTable.vip, 1);
			}
			
			Page<MassModel> page = MassModel.MASS.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page.getList()) {
				list.add(RspMass.createMass(mass));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/**
	 * 获取最新创建社区{@link ReqPage}
	 */
	public void massNewPage() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(MassTable.Table);
			sqlHelp.sore("desc", MassTable.time);

			Page<MassModel> page = MassModel.MASS.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page.getList()) {
				list.add(RspMass.createMass(mass));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 获取社团信息
	 * 
	 * @return
	 */
	public void getMass() {
		try {
			ReqMassQuery req = this.getRequestObject(ReqMassQuery.class);

			MassModel mass = MassModel.MASS.findById(req.getMassId());

			if (mass != null) {
				RspMass mRspMass = RspMass.createMass(mass);

				// 今天发帖数量，评论数量
				SQLHelp sql = new SQLHelp(NoteTable.Table);

				SQLHelp messageSQL = new SQLHelp(MessageTable.Table);
				messageSQL.addWhereEqualTo(MessageTable.massId, mass.getId());
				sql.addWhereEqualTo(NoteTable.massId, mass.getId());

				List<NoteModel> notes = NoteModel.NOTE
						.find(sql.build() + " AND TO_DAYS(" + NoteTable.time + ")=TO_DAYS(NOW())");
				mRspMass.todayNoteSize = notes == null ? 0 : notes.size();

				List<MessageModel> message = MessageModel.MESSAGE
						.find(messageSQL.build() + " AND TO_DAYS(" + MessageTable.time + ")=TO_DAYS(NOW())");
				mRspMass.todayMsgSize = message == null ? 0 : message.size();

				this.renderJson(ReturnData.ok(mRspMass));
			} else {
				this.renderJson(ReturnData.error(103, "未查询到相关信息"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e" + e));
		}
	}

	/***
	 * 获取搜索所有社区 {@link ReqMassSearch}
	 */
	public void massSearchPage() {
		try {
			ReqMassSearch req = this.getRequestObject(ReqMassSearch.class);
			String like = this.getEncoder(req.getContent());
			SQLHelp sqlHelp = new SQLHelp(MassTable.Table);
			sqlHelp.addWhereMatches(like,MassTable.title, MassTable.content);
			sqlHelp.sore("desc", MassTable.size);

			Page<MassModel> page = MassModel.MASS.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page.getList()) {
				list.add(RspMass.createMass(mass));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/***
	 * 获取用户所有社区 {@link }
	 */
	public void massUserPage() {
		try {
			ReqPage req = this.getRequestObject(ReqPage.class);
			SQLHelp sqlHelp = new SQLHelp(MassTable.Table);
			sqlHelp.addWhereEqualTo(MassTable.userId, req.getUserId());

			sqlHelp.sore("desc", MassTable.size, MassTable.time, MassTable.vip);

			Page<MassModel> page = MassModel.MASS.paginate(req.getNowPage(), req.getPageSize(), sqlHelp.getSelect(),
					sqlHelp.buildFrom());

			List<Object> list = new ArrayList<Object>();
			for (MassModel mass : page.getList()) {
				list.add(RspMass.createMass(mass));
			}

			this.renderJson(ReturnData.ok(new Page<>(list, page.getPageNumber(), page.getPageSize(),
					page.getTotalPage(), page.getTotalRow())));

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/**
	 * 新增 {@link ReqMassAdd}
	 */
	public void massAdd() {
		try {
			ReqMassAdd req = this.getRequestObject(ReqMassAdd.class);

			MassModel mass = new MassModel();

			mass.setTime(new Date());
			mass.setUserId(req.getUserId());
			mass.setVersion(1);
			mass.setTitle(this.getEncoder(req.getTitle()));
			mass.setContent(this.getEncoder(req.getContent()));
			mass.setUrl(req.getUrl());
			mass.setVip(req.getVip());
			mass.setWealth(req.getWealth());

			if (mass.save()) {
				this.putTask(new TaskUserWealthCharm(req.getUserId(), Const.CHARM_MASS_ADD, Const.WEALTH_MASS_ADD));
		
				this.renderJson(ReturnData.ok(true));
			} else {
				this.renderJson(ReturnData.error(103, "新建失败"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e" + e));
		}
	}

	/**
	 * 编辑社团信息 {@link ReqMassUpdate}
	 */
	public void massUpdate() {
		try {
			ReqMassUpdate req = this.getRequestObject(ReqMassUpdate.class);
			MassModel mass = MassModel.MASS.findById(req.getMassId());
			if (mass == null) {
				this.renderJson(ReturnData.error(101, "未查询到相关信息"));
				return;
			}

			if (mass.getUserId() == req.getUserId()) {
				MassModel massModel = new MassModel();
				massModel.setId(req.getMassId());
				massModel.setTitle(req.getTitle());
				massModel.setContent(req.getContent());
				massModel.setUrl(req.getUrl());
				massModel.setVip(mass.getVip());
				if (massModel.update()) {
					this.renderJson(ReturnData.ok(true));
				} else {
					this.renderJson(ReturnData.error(103, "更新失败"));
				}
			} else {
				this.renderJson(ReturnData.error(102, "没有相关权限"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

	/**
	 * 删除社团 {@link ReqMassDel}
	 */
	public void massDel() {
		try {
			ReqMassDel req = this.getRequestObject(ReqMassDel.class);
			MassModel mass = MassModel.MASS.findById(req.getMassId());
			if (mass == null) {
				this.renderJson(ReturnData.error(101, "未查询到相关信息"));
				return;
			}

			if (mass.getUserId() == req.getUserId()) {
				if (mass.delete()) {
					this.putTask(new TaskUserWealthCharm(req.getUserId(),Const.CHARM_MASS_DEL, Const.WEALTH_MASS_DEL));
			
					this.renderJson(ReturnData.ok(true));
				} else {
					this.renderJson(ReturnData.error(103, "删除失败"));
				}

			} else {
				this.renderJson(ReturnData.error(102, "没有相关权限"));
			}

		} catch (Exception e) {
			this.renderJson(ReturnData.error(5000, "操作失败 e:" + e));
		}
	}

}
